<script setup lang="ts">
import type { InputNumberBoxEvent } from '@/components/vk-data-input-number-box/vk-data-input-number-box';
import { putMemberCartBySkuIdAPI } from '@/services/cart';
import {
  getMemberOrderPreAPI,
  getMemberOrderPreNowAPI,
  getMemberOrderRepurchaseByIdAPI,
  postMemberOrderAPI,
} from '@/services/order';
import { useAddressStore } from '@/stores/modules/address';
import type { OrderPreResult } from '@/types/order';
import { onLoad } from '@dcloudio/uni-app';
import { computed, ref } from 'vue';

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync();
// 订单备注
const buyerMessage = ref('');
// 配送时间
const deliveryList = ref([
  { type: 1, text: '时间不限 (周一至周日)' },
  { type: 2, text: '工作日送 (周一至周五)' },
  { type: 3, text: '周末配送 (周六至周日)' },
]);
// 当前配送时间下标
const activeIndex = ref(0);
// 当前配送时间
const activeDelivery = computed(() => deliveryList.value[activeIndex.value]);
// 修改配送时间
const onChangeDelivery: UniHelper.SelectorPickerOnChange = (ev) => {
  activeIndex.value = ev.detail.value;
};
// 页面参数
const query = defineProps<{
  skuId?: string;
  count?: string;
  addressId?: string;
  orderId?: string;
}>();
// 获取订单数据
const orderList = ref<OrderPreResult>();
const getMemeberOrderPreData = async () => {
  uni.showLoading({ title: '加载中...', mask: true });
  // 是否有立即购买参数
  if (query.skuId && query.count) {
    // 立即购买
    const res = await getMemberOrderPreNowAPI({
      skuId: query.skuId,
      count: query.count,
      addressId: query.addressId,
    });
    orderList.value = res.result;
    uni.hideLoading();
  } else if (query.orderId) {
    // 再次购买
    const res = await getMemberOrderRepurchaseByIdAPI(query.orderId);
    orderList.value = res.result;
    uni.hideLoading();
  } else {
    // 预付订单
    const res = await getMemberOrderPreAPI();
    orderList.value = res.result;
    uni.hideLoading();
  }
};

// 修改商品数量
const onChangeCount = async (event: InputNumberBoxEvent) => {
  await putMemberCartBySkuIdAPI(event.index, { count: event.value });
};

// 计算商品总价
const totalPrice = computed(() => {
  return orderList.value?.goods
    .reduce((sum, item) => sum + Number(item.payPrice) * item.count, 0)
    .toFixed(2);
});
// 计算商品总件数
const totalCount = computed(() => {
  return orderList.value?.goods.reduce((sum, item) => sum + item.count, 0);
});
// 计算应付金额
const totalPayPrice = computed(() => {
  if (totalPrice.value) {
    return (+totalPrice.value! + orderList.value?.summary.postFee!).toFixed(2);
  }
});
// 初始化调用
onLoad(() => {
  getMemeberOrderPreData();
});

// 收货地址
const addressStore = useAddressStore();
const selectAddress = computed(() => {
  return (
    addressStore.selectAddress ||
    orderList.value?.userAddresses.find((item) => item.isDefault)
  );
});

// 提交订单
const onOrderSubmit = async () => {
  // 没有选择收货地址提醒
  if (!selectAddress.value?.id) {
    return uni.showToast({ icon: 'none', title: '请选择收货地址' });
  }
  // 发送请求
  const res = await postMemberOrderAPI({
    addressId: selectAddress.value.id,
    buyerMessage: buyerMessage.value,
    deliveryTimeType: activeDelivery.value.type,
    goods: orderList.value!.goods.map((item) => ({
      skuId: item.skuId,
      count: item.count,
    })),
    payType: 1,
    payChannel: 2,
  });
  // 关闭当前页面，跳转到订单详情，传递订单id
  uni.redirectTo({ url: `/pagesOrder/detail/detail?id=${res.result.id}` });
};
</script>

<template>
  <scroll-view scroll-y class="scroll-view">
    <!-- 收货地址 -->
    <navigator
      v-if="selectAddress"
      class="shipment"
      hover-class="none"
      url="/pagesMember/address/address?from=order"
    >
      <view class="user">
        {{ selectAddress.receiver }} {{ selectAddress.contact }}
      </view>
      <view class="address">
        {{ selectAddress.fullLocation }} {{ selectAddress.address }}
      </view>
      <text class="icon icon-right"></text>
    </navigator>
    <navigator
      v-else
      class="shipment"
      hover-class="none"
      url="/pagesMember/address/address?from=order"
    >
      <view class="address"> 请选择收货地址 </view>
      <text class="icon icon-right"></text>
    </navigator>

    <!-- 商品信息 -->
    <view class="goods" v-for="item in orderList?.goods">
      <navigator
        :key="item.skuId"
        :url="`/pages/goods/goods?id=${item.id}`"
        class="item"
        hover-class="none"
      >
        <image class="picture" :src="item.picture" />
        <view class="meta">
          <view class="name ellipsis"> {{ item.name }}</view>
          <view class="attrs">{{ item.attrsText }}</view>
          <view class="prices">
            <view class="pay-price symbol">{{ item.payPrice }}</view>
            <view class="price symbol">{{ item.price }}</view>
          </view>
        </view>
      </navigator>
      <view class="count">
        <vk-data-input-number-box
          v-model="item.count"
          :min="1"
          :index="item.skuId"
          @change="onChangeCount"
        ></vk-data-input-number-box>
      </view>
    </view>

    <!-- 配送及支付方式 -->
    <view class="related">
      <view class="item">
        <text class="text">配送时间</text>
        <picker
          :range="deliveryList"
          range-key="text"
          @change="onChangeDelivery"
        >
          <view class="icon-fonts picker">{{ activeDelivery.text }}</view>
        </picker>
      </view>
      <view class="item">
        <text class="text">订单备注</text>
        <input
          class="input"
          :cursor-spacing="30"
          placeholder="选题，建议留言前先与商家沟通确认"
          v-model="buyerMessage"
        />
      </view>
    </view>

    <!-- 支付金额 -->
    <view class="settlement">
      <view class="item">
        <text class="text">商品总价: </text>
        <text class="number symbol">{{ totalPrice }}</text>
      </view>
      <view class="item">
        <text class="text">运费: </text>
        <text class="number symbol">{{
          orderList?.summary.postFee.toFixed(2)
        }}</text>
      </view>
    </view>
  </scroll-view>

  <!-- 吸底工具栏 -->
  <view
    class="toolbar"
    :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }"
  >
    <view class="total-pay symbol">
      <text class="selected-count">共{{ totalCount }}件</text>
      <text class="text">合计:</text>
      <text class="number">{{ totalPayPrice }}</text>
    </view>
    <view class="button" @tap="onOrderSubmit"> 提交订单 </view>
  </view>
</template>

<style lang="scss">
:host {
  background-color: #f4f4f4;
  // height: 100vh;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
  overflow: hidden;
  margin-bottom: 85px;
}
.symbol .number::before {
  content: '¥';
  font-size: 80%;
  margin-right: 5rpx;
}
.symbol {
  margin-right: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  .text {
    font-size: 15px;
    color: #333;
    font-weight: bold;
    margin-right: 10rpx;
  }
  .selected-count {
    font-size: 14px;
    color: #888;
    margin-right: 8rpx;
    letter-spacing: 0.2em;
  }
}

.shipment {
  margin: 20rpx;
  padding: 30rpx 30rpx 30rpx 84rpx;
  font-size: 26rpx;
  border-radius: 10rpx;
  background: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/locate.png)
    20rpx center / 50rpx no-repeat #fff;
  position: relative;

  .icon {
    font-size: 36rpx;
    color: #333;
    transform: translateY(-50%);
    position: absolute;
    top: 50%;
    right: 20rpx;
  }

  .user {
    color: #333;
    margin-bottom: 5rpx;
  }

  .address {
    color: #666;
    width: 90%;
  }
}

.goods {
  margin: 20rpx;
  display: flex;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;
  position: relative;
  // 商品数量
  .count {
    position: absolute;
    bottom: 20rpx;
    right: 5rpx;

    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 200rpx;
    height: 48rpx;

    .text {
      height: 100%;
      padding: 0 20rpx;
      font-size: 32rpx;
      color: #444;
      background-color: #f6f6f6;
    }

    .input {
      height: 100%;
      text-align: center;
      border-radius: 4rpx;
      font-size: 24rpx;
      color: #444;
      background-color: #f6f6f6;
    }
  }

  .item {
    display: flex;
    padding: 30rpx 0;
    border-top: 1rpx solid #eee;

    &:first-child {
      border-top: none;
    }

    .picture {
      width: 170rpx;
      height: 170rpx;
      border-radius: 10rpx;
      margin-right: 20rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      position: relative;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .attrs {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 6rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .prices {
      display: flex;
      align-items: baseline;
      margin-top: 6rpx;
      font-size: 28rpx;

      .pay-price {
        margin-right: 10rpx;
        color: #ec602b;
      }

      .price {
        font-size: 24rpx;
        color: #999;
        text-decoration: line-through;
      }
    }

    .count {
      position: absolute;
      bottom: 0;
      right: 0;
      font-size: 26rpx;
      color: #444;
    }
  }
}

.related {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .input {
    flex: 1;
    text-align: right;
    margin: 20rpx 0;
    padding-right: 20rpx;
    font-size: 26rpx;
    color: #999;
  }

  .item .text {
    width: 125rpx;
  }

  .picker {
    color: #666;
  }

  .picker::after {
    content: '\e6c2';
  }
}

/* 结算清单 */
.settlement {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .danger {
    color: #ec602b;
  }
}

/* 吸底工具栏 */
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(var(--window-bottom));
  z-index: 1;

  background-color: #fff;
  height: 100rpx;
  padding: 0 20rpx;
  border-top: 1rpx solid #eaeaea;
  display: flex;
  // justify-content: space-between;
  justify-content: flex-end;
  align-items: center;
  box-sizing: content-box;

  .total-pay {
    font-size: 40rpx;
    color: #ec602b;
    font-weight: bold;

    .decimal {
      font-size: 75%;
    }
  }

  .button {
    width: 220rpx;
    text-align: center;
    line-height: 72rpx;
    font-weight: 500;
    font-size: 29rpx;
    color: #fff;
    border-radius: 72rpx;
    background: linear-gradient(90deg, #ed792f, #ec602b);
  }

  .disabled {
    opacity: 0.6;
  }
}
</style>
